﻿using Opc.Ua;
using OPCCollect;
using PDB.DotNetSDK;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OpcUaHelper.Demo
{
	class SimuUpdateTask
	{
		private List<TagInfo> tagList;
		private OpcUaClient uaClient;
		private Thread workThread;
		private bool running;

		public string OpcServer { get; set; }

		public SimuUpdateTask(List<TagInfo> tagList)
		{
			this.tagList = tagList;
			uaClient = null;
			running = true;
			workThread = null;
		}

		public void RunTask()
		{
			workThread = new Thread(TaskWork);
			workThread.IsBackground = true;
			workThread.Start();
		}

		private void TaskWork()
		{
			while (running)
			{
				GetUpdateOpcValues();
				Thread.Sleep(5000);
			}
		}


		private void GetUpdateOpcValues()
		{
			//首先将所有值清空
			foreach (TagInfo tag in tagList)
			{
				tag.OpcValue = null;
			}

			try
			{
				if (uaClient == null)
				{
					uaClient = new OpcUaClient();
					uaClient.ConnectServer(OpcServer).Wait();
				}

				const int BATCH = 100;
				int batch = BATCH;

				int updatevalue = 5;

				for (int i = 0; i < tagList.Count; i += batch)
				{
					batch = (tagList.Count - i) > BATCH ? BATCH : tagList.Count - i;

					string[] nodeIdstrs = new string[batch];
					object[] values = new object[batch];
					NodeId[] nodeIds = new NodeId[batch];
					for (int j = 0; j < batch; j++)
					{
						//本地测试临时修改
						nodeIdstrs[j] = string.Format("ns=2;s=S7-1500RH-System_1.PLC_1.DB001.{0}", tagList[i + j].OpcName);
						nodeIds[j] = new NodeId(string.Format("ns=2;s=S7-1500RH-System_1.PLC_1.DB001.{0}", tagList[i + j].OpcName));
						//nodeIdstrs[j] = string.Format("ns=2;s={0}", tagList[i + j].OpcName);
						//nodeIds[j] = new NodeId(string.Format("ns=2;s={0}", tagList[i + j].OpcName));
					}

					List<DataValue> dataList = uaClient.ReadNodes(nodeIds);
					for (int j = 0; j < batch; j++)
					{
						//获取原有的datavalue
						DataValue oridataValue = dataList[j];
						values[j] = Convert.ToInt32(oridataValue.Value) + updatevalue;
						//为其赋新的值

						//tagList[i + j].OpcValue = dataList[j];
					}
					bool success = uaClient.WriteNodes(nodeIdstrs, values);

					double a = 0;
				}
			}
			catch (Exception ex)
			{
				uaClient = null;
			}
		}
	}
}
